﻿using JST.TPLMS.Contract.IBaseFiles;
using JST.TPLMS.Entitys.Entities;
using Microsoft.AspNetCore.Mvc;
using NPOI.OpenXmlFormats.Dml;

namespace JST.TPLMS.Web.Controllers
{
    /// <summary>
    /// 供应商
    /// </summary>
    public class SupplierController : Controller
    {
        private readonly IUnitOfWork _unitOfWork;

        public SupplierController(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public IActionResult Index()
        {
            var suppliers = _unitOfWork.SupplierRepo.GetAll();
            return View(suppliers);
        }

        #region 创建供应商

        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Create(Supplier obj)
        {
            if (ModelState.IsValid)
            {
                _unitOfWork.SupplierRepo.Add(obj);
                _unitOfWork.Save();
                return RedirectToAction(nameof(Index));
            }
            return View();
        }

        #endregion


        #region 编辑供应商

        public IActionResult Update(int supplierId)
        {
            Supplier? obj = _unitOfWork.SupplierRepo.Get(u => u.Id == supplierId);
            if (obj == null)
            {
                return RedirectToAction("Error", "Home");
            }
            return View(obj);
        }

        [HttpPost]
        public IActionResult Update(Supplier obj)
        {
            if (ModelState.IsValid && obj.Id > 0)
            {
                _unitOfWork.SupplierRepo.Update(obj);
                _unitOfWork.Save();
                return RedirectToAction(nameof(Index));
            }
            return View();
        }

        #endregion

        #region 删除供应商

        public IActionResult Delete(int supplierId)
        {
            Supplier? obj = _unitOfWork.SupplierRepo.Get(u => u.Id == supplierId);
            if (obj == null)
            {
                return RedirectToAction("Error", "Home");
            }
            return View(obj);
        }

        [HttpPost]
        public IActionResult Delete(Supplier obj)
        {
            Supplier? objFromDb = _unitOfWork.SupplierRepo.Get(u => u.Id == obj.Id);
            if (objFromDb is not null)
            {
                _unitOfWork.SupplierRepo.Remove(objFromDb);
                _unitOfWork.Save();
                return RedirectToAction(nameof(Index));
            }

            return View();

        }

        #endregion
    }
}
